package cn.sylinx.hbatis.plugin.statement;

import cn.sylinx.hbatis.ext.res.StatementHandler;
import cn.sylinx.hbatis.log.GLog;

public enum StatementHandlerManager {

	ME;

	private StatementHandler statementHandler = null;

	public static StatementHandlerManager get() {
		return ME;
	}

	public synchronized void init(String statementHandlerClass) {

		if (statementHandler != null) {
			GLog.error("statementHandler can only be instantiated once");
			return;
		}

		if (statementHandlerClass == null) {
			GLog.error("statementHandlerClass CAN NOT BE NULL");
			return;
		}

		try {
			Class<?> clz = Class.forName(statementHandlerClass);
			statementHandler = (StatementHandler) clz.newInstance();
		} catch (Exception e) {
			GLog.error("初始化StatementHandler异常", e);
		}

	}

	public StatementHandler getStatementHandler(String ds) {

		if (statementHandler == null) {
			return null;
		}

		if (statementHandler instanceof DatasourceStatementHandler) {
			return ((DatasourceStatementHandler) statementHandler).get(ds);
		}

		return statementHandler;
	}
}
